package so.shanku.essential.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebChromeClient;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.*;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.view.annotation.event.OnClick;
import com.umeng.socialize.bean.SocializeConfig;
import com.umeng.socialize.sso.UMSsoHandler;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseUIActivity;
import so.shanku.essential.adapter.LinkProductAdapter;
import so.shanku.essential.adapter.RelationProductAdapter;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Constant;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.StringUtil;
import so.shanku.essential.utils.Utils;
import striveen.util.used.view.view.XListView;
import striveen.util.used.view.view.gridview.PLA_AdapterView;
import striveen.util.used.view.view.gridview.XGridView;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Jaelyn on 2015/9/8 0008.
 * 发现详情
 */
public class FindDetailActivity extends BaseUIActivity {
    private LinearLayout head_layout;//头部布局

    /**
     * 品牌logo
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.find_contents_wb)
    private WebView find_contents_wb;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.myProgressBar)
    private ProgressBar myProgressBar;

    /**
     * 评论布局
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.msg_iv)
    private ImageView msg_iv;
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.more_iv)
    private ImageView more_iv;

    /**
     * 相关商品的title
     */
    @com.lidroid.xutils.view.annotation.ViewInject(R.id.relation_goods)
    private LinearLayout relation_goods_title_layout;


    //相关商品
    @ViewInject(id = R.id.relation_goods_xgv)
    private XListView relation_goods_xgv;
    private LinkProductAdapter relationProductAdapter;

    /**
     * 只加载网页
     */
    @ViewInject(id = R.id.only_webView)
    private ScrollView only_webView_layout;

    private String discoredId;//发现id

    private String comments = "0";
    private JsonMap goodsDetailDatas;//商品强请
    private int pageSize = 10;
    private int currentPage = 0;
    /**
     * 商品的信息数据
     */
    private List<JsonMap<String, Object>> goodsDatas;

    private JsonMap findDatas;
    private int praiseNum = 0;
    private String shareContent;
    private String isCollection;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.find_detail_layout);
        setCenter_title(R.string.find);
        setMenuView();
        head_layout = (LinearLayout) getLayoutInflater().inflate(R.layout.find_detail_head_layout, null);
        ViewUtils.inject(this, head_layout);
        only_webView_layout.addView(head_layout);
        only_webView_layout.setVisibility(View.VISIBLE);
        relationProductAdapter = new LinkProductAdapter(this);


        discoredId = getIntent().getStringExtra(Constant.ID);

        relation_goods_xgv.setPullRefreshEnable(false);
        relation_goods_xgv.setPullLoadEnable(false);
        relation_goods_xgv.setOnItemClickListener(onItemClickListener);
        relation_goods_xgv.setXListViewListener(loadMoreListener);

        String formartStr = GetDataConfing.Url_Base + "FindBrand/AppFindBrandDetai?userId=%s&disId=%s";
        String url = String.format(formartStr, Utils.getUserId(mContext), discoredId);
        setWebViewFeature();
        find_contents_wb.loadUrl(url);

        getGoodsDetail();
        //getRelationGoods();
    }


    private void setMenuView() {
        menu_layout.removeAllViews();
        View findMenuLayout = getLayoutInflater().inflate(R.layout.find_menu_layout, null);
        menu_layout.addView(findMenuLayout);
        ViewUtils.inject(this, findMenuLayout);
    }

    private AdapterView.OnItemClickListener onItemClickListener = new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            if (position > 0) {
                int goodsType = goodsDatas.get(position - 1).getInt("goodsType");
                if (goodsType == 1) {
                    String goodsId = goodsDatas.get(position - 1).getStringNoNull("ProductId");
                    seeProductDetail(goodsId);
                }
            }
        }
    };

    /**
     * 获取相关商品
     */
    private XListView.IXListViewListener loadMoreListener = new XListView.IXListViewListener() {
        @Override
        public void onRefresh() {
        }

        @Override
        public void onLoadMore() {
            getRelationGoods();
        }
    };

    /**
     * 获取相关商品  {DiscoverId:3, currentPage:1,pageSize:10}
     */
    private void getRelationGoods() {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        params.put("currentPage", currentPage + 1);
        params.put("pageSize", pageSize);
        params.put("DiscoverId", discoredId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetDiscoverMoreProduct);
        queue.setWhat(GetDataConfing.What_GetDiscoverMoreProduct);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        getDataUtil.getData(queue);

    }


    /**
     * {DiscoverId:3}
     * 获取商品详情
     */
    private void getGoodsDetail() {
        loadingToast.show();
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        if (Utils.isHasLogin(this)) {
            params.put("UserInfoId", Utils.getUserId(this));
        }
        params.put("DiscoverId", discoredId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetDiscoverDetails);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetDiscoverDetails);
        getDataUtil.getData(queue);
    }

    /**
     * 校验数据 显示无数据等
     * <p/>
     * 是否请求正常 网络错误且数据为空的话显示网络异常界面 提供刷新的接口
     *
     * @param data_server
     */
    private void validateData(List<JsonMap<String, Object>> data_server) {
        relation_goods_xgv.requestLayout();
        find_contents_wb.requestLayout();
        if (goodsDatas.size() == 0) {
            toast.showToast(R.string.no_shop_goods_data);
            relation_goods_xgv.setPullLoadEnable(false);
            return;
        }
        if (data_server.size() == 0 || data_server.size() % pageSize != 0) {
            relation_goods_xgv.setPullLoadEnable(false);
        } else {
            relation_goods_xgv.setPullLoadEnable(true);
        }
    }

    private GetServicesDataUtil.IGetServicesDataCallBack callBack = new GetServicesDataUtil.IGetServicesDataCallBack() {

        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isCodeSuccess(mContext, entity.getInfo())) {
                    if (entity.what == GetDataConfing.What_GetDiscoverMoreProduct) {
                        List<JsonMap<String, Object>> data_server = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info);
                        setData(data_server);
                        validateData(data_server);
                    } else if (entity.what == GetDataConfing.What_GetDiscoverDetails) {
                        try {
                            goodsDetailDatas = JsonParseHelper.getJsonMap_List_JsonMap(entity.getInfo(), JsonKeys.Key_Info).get(0);
                            refreshGoodsDetail(goodsDetailDatas);
                            //getRelationGoods();
                        } catch (Exception e) {
                            e.printStackTrace();
                            toast.showToast(R.string.server_error);
                            finish();
                        }
                    } else if (entity.what == GetDataConfing.What_GetDiscoverPraise) { //点赞
                        JsonMap<String, Object> data = JsonParseHelper
                                .getJsonMap(entity.getInfo());
                        String msg = data.getString(JsonKeys.Key_Msg);
                        toast.showToast(msg);
                         isCollection=data.getJsonMap(JsonKeys.Key_Info).getStringNoNull("isCollection");
//                        try {
//                            String msg = data.getString(JsonKeys.Key_Msg);
////						toast.showToast(msg);
//                            if (data.getBoolean("IsFocus")) {
//                                praiseNum++;
//                                setPraiseNumAndStaues(praiseNum, true);
//                            } else {
//                                praiseNum--;
//                                setPraiseNumAndStaues(praiseNum, false);
//                            }
//                        } catch (Exception e) {
//                            e.printStackTrace();
//                        }
                    }
                }
            } else {
                //ShowGetDataError.showNetError(mContext);
            }
            loadingToast.dismiss();
            relation_goods_xgv.stopLoadMore();
        }

    };


    private void setData(List<JsonMap<String, Object>> temp_data) {

        if (currentPage == 0) {
            goodsDatas = temp_data;
            relationProductAdapter.setDatas(goodsDatas);
            //ptr_list.setAdapter(shoppingAdapter);
            relation_goods_xgv.setAdapter(relationProductAdapter);
            relationProductAdapter.notifyDataSetChanged();
            refreshLayoutView();
        } else {
            goodsDatas.addAll(temp_data);
            relationProductAdapter.notifyDataSetChanged();
        }
        currentPage++;

    }

    private void refreshLayoutView() {

//        relation_goods_xgv.forceLayout();
//        find_contents_wb.forceLayout();
//        find_contents_wb.invalidate();
//        relation_goods_xgv.invalidate();
//        relation_goods_xgv.invalidateViews();
//        relation_goods_xgv.postInvalidate();
//        relation_goods_xgv.onGlobalLayout();

    }

    private void refreshGoodsDetail(JsonMap goodsDatas) {
        findDatas = goodsDatas;
        setCenter_title(goodsDatas.getStringNoNull("SubTitle"));
//		setGoodsDiscribe(goodsDatas.getStringNoNull("Content"));
//		String brandLogoPath = goodsDatas.getStringNoNull("ViceImage");
//		if (MyApplication.getInstance().getBitmapHashMap().containsKey(brandLogoPath)) {
//			find_detail_goods_logo_iv.setImageBitmap((MyApplication.getInstance().getBitmapHashMap().get(brandLogoPath)));
//		} else {
//			ImageLoader.getInstance().displayImage(brandLogoPath, find_detail_goods_logo_iv, MyApplication.getInstance().getBrandDefaultOption(), new ImageLoaderBitmapCallBack());
//
//			//bitmapUtils.display(holder.programIcon, imageurl, customBitmapLoadCallBack);
//		}

        String commentsCounts = goodsDatas.getStringNoNull("CommentsCount", "0");
//        String praiseCounts = goodsDatas.getStringNoNull("PraiseCount", "0");
//        boolean isPraiseed = goodsDatas.getBoolean("IsPraise");
//        try {
//            praiseNum = Integer.parseInt(praiseCounts);
//        } catch (NumberFormatException e) {
//            e.printStackTrace();
//        }
        //setPraiseNumAndStaues(praiseNum, isPraiseed);
        isCollection=goodsDatas.getStringNoNull("isCollection");
        setCommentsNum(commentsCounts);
        int relationGoodsNum = goodsDatas.getInt("relationGoodsNum", 0);
        if (relationGoodsNum > 0) {
            only_webView_layout.removeAllViews();
            only_webView_layout.setVisibility(View.GONE);
            relation_goods_xgv.setVisibility(View.VISIBLE);
            relation_goods_xgv.addHeaderView(head_layout);
            relation_goods_xgv.setAdapter(relationProductAdapter);
            getRelationGoods();
        } else {
            only_webView_layout.setVisibility(View.VISIBLE);
            relation_goods_xgv.setVisibility(View.GONE);
            relation_goods_title_layout.setVisibility(View.GONE);
        }
    }

    private void setWebViewFeature() {
        WebSettings webSettings = find_contents_wb.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webSettings.setAllowFileAccess(true);
        webSettings.setAllowContentAccess(true);
        webSettings.setAppCacheEnabled(true);
        webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
        webSettings.setDomStorageEnabled(true);
        webSettings.setGeolocationEnabled(true);
        webSettings.setLoadsImagesAutomatically(true);
        webSettings.setEnableSmoothTransition(true);
        //webSettings.setBuiltInZoomControls(true);
        webSettings.setLightTouchEnabled(true);
        //webSettings.setSupportZoom(true);
        find_contents_wb.setHapticFeedbackEnabled(true);
        //register_agreement_wv.setWebViewClient(new MyWebUriViewClient());
        find_contents_wb.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                if (newProgress == 100) {
                    myProgressBar.setVisibility(View.INVISIBLE);
                    if (relationProductAdapter != null)
                        relationProductAdapter.notifyDataSetChanged();
                    refreshLayoutView();
                } else {
                    if (newProgress == 50) {
                        if (relationProductAdapter != null)
                            relationProductAdapter.notifyDataSetChanged();
                        refreshLayoutView();
                    }
                    if (View.VISIBLE != myProgressBar.getVisibility()) {
                        myProgressBar.setVisibility(View.VISIBLE);
                    }
                    myProgressBar.setProgress(newProgress);
                }
                super.onProgressChanged(view, newProgress);
            }

        });
        webSettings.setUseWideViewPort(false);
        webSettings.setLoadWithOverviewMode(true);
    }

    /**
     * 设置点赞人数
     *
     * @param praiseCounts
     * @param isPraiseed
     */
//    private void setPraiseNumAndStaues(int praiseCounts, boolean isPraiseed) {
//        praise_layout.setSelected(isPraiseed);
//        praise_tv.setText("" + praiseCounts);
//    }

    /**
     * 设置评论人数
     *
     * @param commentsCounts
     */
    private void setCommentsNum(String commentsCounts) {
        comments = getString(R.string.find_detail_comments_num);
        //comments_num_tv.setText(String.format(comments, commentsCounts));
    }

    /**
     * 设置商品描述
     *
     * @param str
     */
    private void setGoodsDiscribe(String str) {
//		if (!TextUtils.isEmpty(str)) {
//			find_detail_goods_discribe_tv.setText("\t\t\t\t" + str);
//			find_detail_goods_discribe_tv.setVisibility(View.VISIBLE);
//		}
    }

    /**
     * 分享
     */
    public void share_iv_click() {
        JsonMap jsonMap_temp = findDatas;
        String shareLogo = jsonMap_temp.getStringNoNull("ViceImage");
        String shareTitle = jsonMap_temp.getStringNoNull("SubTitle");

        if (TextUtils.isEmpty(shareContent)) {
            shareContent = jsonMap_temp.getStringNoNull("SubTitle");
        }
        String shareUrl = "FindBrand/FindBrandDetail?disId=" + discoredId;

        MyApplication.getInstance().showShareCompont(this, shareLogo, shareUrl, shareTitle, shareContent);
    }

    /**
     * 收藏文章
     */
    private void collect_tv_click() {
        if (Utils.isFastClick()) {
            return;
        }
        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        params.put("UserInfoId", Utils.getUserId(this));
        params.put("DiscoverId", discoredId);
        GetDataQueue queue = new GetDataQueue();
        queue.setActionName(GetDataConfing.Action_GetDiscoverPraise);
        queue.setParamsNoJson(params);
        queue.setCallBack(callBack);
        queue.setWhat(GetDataConfing.What_GetDiscoverPraise);
        getDataUtil.getData(queue);
    }

    /**
     * 所有评论
     *
     * @param view
     */
    @OnClick(R.id.msg_iv)
    public void msg_iv_click(View view) {
//        if (TextUtils.isEmpty(comments) || comments.equalsIgnoreCase("0")) {
//            return;
//        }
        Intent intent = new Intent(this, FindCommentsActivity.class);
        intent.putExtra(ExtraKeys.Key_Msg1, discoredId);
        intent.putExtra(ExtraKeys.Key_Msg2, findDatas.getStringNoNull("SubTitle"));
        jumpTo(intent, false);
    }


    /**
     * 所有评论
     *
     * @param view
     */
    @OnClick(R.id.more_iv)
    public void more_iv_click(View view) {
        showPopWindowView();
    }


    public PopupWindow popupWindow;
    private TextView collect_tv;
    private TextView share_tv;
    private TextView cancel_tv;


    private void showPopWindowView() {
        if (popupWindow == null) {
            View view = getLayoutInflater().inflate(R.layout.find_more_menu, null);
            popupWindow = new PopupWindow(view,
                    ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            popupWindow.setContentView(view);
            popupWindow.setAnimationStyle(R.style.popupAnimation);
            collect_tv = (TextView) view.findViewById(R.id.collect_tv);
            share_tv = (TextView) view.findViewById(R.id.share_tv);
            cancel_tv = (TextView) view.findViewById(R.id.cancel_tv);
            if (isCollection.equals("1")){
                collect_tv.setText(R.string.cancel_collection);
            }
            View select_v = (View) view.findViewById(R.id.select_v);
            collect_tv.setOnClickListener(myclick);
            share_tv.setOnClickListener(myclick);
            select_v.setOnClickListener(myclick);
            cancel_tv.setOnClickListener(myclick);
            popupWindow.showAtLocation(more_iv, Gravity.NO_GRAVITY, 0, 0);

        } else if (!popupWindow.isShowing()) {
            popupWindow.showAtLocation(more_iv, Gravity.NO_GRAVITY, 0, 0);
        }
    }


    /**
     * “我的”点击事件
     */
    View.OnClickListener myclick = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            int id = v.getId();
            popupWindow.dismiss();
            switch (id) {
                case R.id.share_tv:
                    share_iv_click();
                    break;
                case R.id.collect_tv:
                    collect_tv_click();
                    break;
                case R.id.select_v:
                    break;
                case R.id.cancel_tv:
                    //退出登录
                    break;

                default:
                    break;
            }
        }
    };


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        /**使用SSO授权必须添加如下代码 */

//        UMSocialService umSocialService=MyApplication.getInstance().getmController();
//        if(umSocialService!=null) {
//            UMSsoHandler ssoHandler =umSocialService.getConfig().getSsoHandler(requestCode);
//            if (ssoHandler != null) {
//                ssoHandler.authorizeCallBack(requestCode, resultCode, data);
//            }
//        }

        UMSsoHandler ssoHandler = SocializeConfig.getSocializeConfig().getSsoHandler(requestCode);
        if (ssoHandler != null) {
            ssoHandler.authorizeCallBack(requestCode, resultCode, data);
        }
    }

}